/**
 * @param {number[]} prices
 * @return {number}
 */
/**
 * i将prices划分为两个区间
 * 找到第一个区间最大的值，第二个区间最大的值，加起来
 * 然后取加起来和的最大值
 */
var maxProfit = function (prices) {
    let len = prices.length,  profitArr = new Array(len).fill(0), profit = 0;
    let currentMax = prices[len - 1], currentLeftMin = prices[0], res = 0;
    for(let j = len - 2; j >= 0; j--) {
            // 如果当前价格比前面的价格高或相等
            if(prices[j] >= currentMax) {
                currentMax = prices[j] // 更新当前区间最大值
                profitArr[j] = profitArr[j + 1] // 最大利润不更新，等于下一个的利润
            } else {
                // 当前价格比后面最大值小，更新
                profit = currentMax - prices[j] > profit ? currentMax - prices[j] : profit
                profitArr[j] = profit
            }
    }
    profit = 0
    for(let i = 0; i < len; i++) {
        if(prices[i] <= currentLeftMin) {
            currentLeftMin = prices[i]
        } else {
            profit = prices[i] - currentLeftMin > profit ? prices[i] - currentLeftMin : profit
        }
        res = profit + profitArr[i] > res ? profit + profitArr[i] : res
    }
    return res
};
console.log(maxProfit([3, 3, 5, 0, 0, 3, 1, 4]));
console.log(maxProfit([1, 2, 3, 4, 5]));
console.log(maxProfit([7, 6, 4, 3, 1]));
console.log(maxProfit([1]));
console.log(maxProfit([1, 2, 4, 2, 5, 7, 2, 4, 9, 0]));